﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IGolovkine.ShoutCastRipper.Service.Contracts;
using System.Threading;

namespace IGolovkine.ShoutCastRipper.Service
{
    internal class StationRipperEventQueue 
    {
        private readonly Queue<StationRipperEventDataContract> _events;
        private readonly int _maxSize;
        private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();

        internal StationRipperEventQueue(int maxSize)
        {
            _maxSize = maxSize;
            _events = new Queue<StationRipperEventDataContract>();
        }

        internal void Enqueue(StationRipperEventDataContract evt)
        {
            _lock.EnterWriteLock();
            try
            {
                _events.Enqueue(evt);
                if (_events.Count > _maxSize)
                {
                    _events.Dequeue();
                }
            }
            finally
            {
                _lock.ExitWriteLock();
            }
        }

        internal IEnumerable<StationRipperEventDataContract> GetEventsSince(DateTime since)
        {
            _lock.EnterReadLock();
            try
            {
                return _events.Where(r => r.Time >= since);
            }
            finally
            {
                _lock.ExitReadLock();
            }
        }
    }
}
